package cn.tedu.ivos3.dictoption.service.impl;

import cn.tedu.ivos3.base.exception.ServiceException;
import cn.tedu.ivos3.base.response.StatusCode;
import cn.tedu.ivos3.dict.mapper.DictMapper;
import cn.tedu.ivos3.dict.pojo.dto.DictQuery;
import cn.tedu.ivos3.dict.pojo.vo.DictVO;
import cn.tedu.ivos3.dictoption.mapper.DictOptionMapper;
import cn.tedu.ivos3.dictoption.pojo.dto.DictOptionQuery;
import cn.tedu.ivos3.dictoption.pojo.dto.DictOptionSaveParam;
import cn.tedu.ivos3.dictoption.pojo.entity.DictOption;
import cn.tedu.ivos3.dictoption.pojo.vo.DictOptionVO;
import cn.tedu.ivos3.dictoption.service.DictOptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class DictOptionServiceImpl implements DictOptionService {
    @Autowired
    DictOptionMapper dictOptionMapper;
    @Autowired
    DictMapper dictMapper;

    @Override
    public List<DictOptionVO> selectDictOption(DictOptionQuery dictOptionQuery) {
        log.debug("查询字典项业务参数：", dictOptionQuery);
        List<DictOptionVO> list = dictOptionMapper.selectDictOption(dictOptionQuery);
        return list;
    }

    @Override
    public void saveOption(DictOptionSaveParam dictOptionSaveParam) {
        log.debug("保存/编辑字典项业务数据：{}", dictOptionSaveParam);
        DictOption dictOption = new DictOption();
        BeanUtils.copyProperties(dictOptionSaveParam, dictOption);
        if (dictOption.getId() == null) {
            dictOption.setCreateTime(new Date());
            dictOptionMapper.insert(dictOption);
        } else {
            dictOption.setUpdateTime(new Date());
            dictOptionMapper.update(dictOption);
        }
    }

    @Override
    public void deleteDictOption(Long id) {
        log.debug("删除字典项：{}", id);
        dictOptionMapper.delete(id);
    }

    @Override
    public List<DictOptionVO> selectDictOptionByCode(String code) {
        log.debug("根据字典code查询所有字典业务：{}", code);
        //在dict中通过code查对应的字典集合，在字典集合中获得字典项dictId=id
        //需要根据字典code将对应的字典VO查出来
        DictQuery dictQuery = new DictQuery();
        dictQuery.setCode(code);
        List<DictVO> dictVOList = dictMapper.selectDict(dictQuery);
        //若查询结果正常，取出此字典id，方便下一步查询
        if (dictVOList != null && dictVOList.size() > 0) {
            DictVO dictVO = new DictVO();
            //封装字典项查询对象
            DictOptionQuery dictOptionQuery = new DictOptionQuery();
            dictOptionQuery.setDictId(dictVO.getId());
            //查询字典项
            List<DictOptionVO> dictOptionVOList = dictOptionMapper.selectDictOption(dictOptionQuery);
            return dictOptionVOList;
        } else {
            throw new ServiceException(StatusCode.DATA_UNEXISTS);
        }
    }

}
